<?php

use Typecho\Plugin;
use Typecho\Common;
use Typecho\Widget\Helper\Form\Element\Checkbox;
use Typecho\Widget\Helper\Form\Element\Text;
use Typecho\Widget\Helper\Form\Element\Textarea;
use Typecho\Widget\Helper\Form\Element\Radio;
use Utils\Helper;
use Widget\Notice;
use Widget\Options;

if (!defined('__TYPECHO_ROOT_DIR__')) exit;

/**
 * 获取 Options
 * @return Options
 */
function getOptions(): Options
{
  return Helper::options();
}

function getDb()
{
  return Typecho_Db::get();
}

/**
 * 获取顶部菜单
 */
function gettopMenu()
{
  return json_decode(getOptions()->topMenu, true);
}

/**
 * 获取底部菜单
 */
function getbottomMenu()
{
  return json_decode(getOptions()->bottomMenu, true);
}

/**
 * 主题配置
 * @param $form
 * @return void
 */
function themeConfig($form)
{

  $icon = new Text(
    'icon',
    null,
    null,
    _t('浏览器标签页图标'),
    _t('在这里填入一个图片 URL 地址, 以在浏览器标签栏显示一个 ICON，默认值为站点路径下 /favicon.ico')
  );
  $form->addInput($icon);

  $enabletx = new Radio(
    'enabletx',
    [
      '1' => _t('开启'),
      '0' => _t('关闭'),
    ],
    '0',
    _t('本地头像'),
    _t('默认关闭，开启后注册用户将使用member.svg，未登录用户使用guest.svg')
  );
  $form->addInput($enabletx);

  $avatarlink = new Typecho_Widget_Helper_Form_Element_Text('avatarlink', NULL, 'https://cravatar.cn/avatar/', _t('自定义avatar头像源'), _t('请输入自定义头像源地址（开启本地头像后失效），推荐：<b class="notice">https://cravatar.cn/avatar/</b>'));
  $form->addInput($avatarlink);

  $cdnAddress = new Typecho_Widget_Helper_Form_Element_Text('cdnAddress', NULL, NULL, _t('主题静态文件的链接地址替换'), _t('请输入你的CDN云存储地址，例如：<b class="notice">https://cdn.xxvv.cn/usr/themes/fantasy/</b>'));
  $form->addInput($cdnAddress);

  $AttUrlReplace = new Typecho_Widget_Helper_Form_Element_Textarea('AttUrlReplace', NULL, NULL, _t('文章内的链接地址替换（建议用在图片等静态资源的链接上）'), _t('按照格式输入你的CDN链接以替换原链接，格式：<br><b class="notice">原地址=替换地址</b><br>原地址与新地址之间用等号“=”分隔，例如：<br><b>//xxvv.cn/usr/uploads/=//cdn.xxvv.cn/usr/uploads/</b><br>可设置多个规则，换行即可，一行一个'));
  $form->addInput($AttUrlReplace);

  $topMenu = new Textarea(
    'topMenu',
    null,
    null,
    '顶部菜单',
    '参考文档：<a href="https://xxvv.cn/archives/150/" target="_blank">《设置文档》</a>'
  );
  $form->addInput($topMenu);
  
  $bottomMenu = new Textarea(
    'bottomMenu',
    null,
    null,
    '底部菜单',
    '参考文档：<a href="https://xxvv.cn/archives/150/" target="_blank">《设置文档》</a>'
  );
  $form->addInput($bottomMenu);

  $stickyPost = new Text(
    'stickyPost',
    null,
    null,
    '置顶文章',
    '格式：文章的ID || 文章的ID || 文章的ID （中间使用两个竖杠分隔）'
  );
  $form->addInput($stickyPost);
  
  $PostAD = new Textarea(
    'PostAD',
    null,
    null,
    '文章广告',
    '将广告代码填入即可'
  );
  $form->addInput($PostAD);

  $startDate = new Text('startDate', null, null, '建站日期', '格式：2008-08-08');
  $form->addInput($startDate);

  $icpCode = new Text('icpCode', null, null, 'ICP备案号', 'ICP备案号');
  $form->addInput($icpCode);
  
  $gaCode = new Text('gaCode', null, null, '公安备案号', '公安备案号');
  $form->addInput($gaCode);
}

/**
 * 获取选项值，无法获取则返回默认值数据
 * @param $name     选项名
 * @param $defaultValue 默认值
 */
function getOptionValueOrDefault($name, $defaultValue)
{
  return getOptions()->$name ? getOptions()->$name : $defaultValue;
}

/**
 * 查找数组选项值，无法获取则返回默认值
 * @param $optionName     名称
 * @param $searchName   数组名
 * @param $defaultValue 默认值
 */
function inArrayOptionValueOrDefault($optionName, $searchName, $defaultValue)
{
  if ($optionValue = getOptions()->$optionName) {
    return in_array($searchName, $optionValue);
  } else {
    return $defaultValue;
  }
}

/**
 * 获取置顶文章
 */
function getStickyPost(): array
{
  $sticky_text = getOptions()->stickyPost;
  if (empty($sticky_text)) {
    return [];
  }
  $sticky_cids = explode('||', strtr($sticky_text, ' ', ''));
  return $sticky_cids;
}

//themeInit函数
function themeInit($archive) {
    
  //评论回复楼层最高999层.这个正常设置最高只有7层
  //Helper::options()->commentsMaxNestingLevels = 999;
  
    if ($archive->is('single')) {
	if (getOptions()->AttUrlReplace) {
			$archive->content = UrlReplace($archive->content);
	}
        $archive->content = image_lazy($archive->content);
    }
//    if ($archive->is('post')) {
//    $archive->content = link_go($archive->content);
//    }
}

//附件CDN
function UrlReplace($obj) {
	$list = explode(PHP_EOL, getOptions()->AttUrlReplace);
	foreach ($list as $tmp) {
		list($old, $new) = explode('=', $tmp);
		$obj = str_replace($old, $new, $obj);
	}
	return $obj;
}

//图片懒加载标签
function image_lazy($content) { 
    return preg_replace('/<img([^>]+)>/i', '<img loading="lazy"$1>', $content);
}

/*//外链跳转
function link_go($content) { 
    $siteUrl = getOptions()->siteUrl;
    return preg_replace_callback(
            '/<a\s+(.*?)href="([^"]+)"(.*?)>/i',
            function ($matches) use ($siteUrl) {
                $url = $matches[2];
                if (strpos($url, $siteUrl) === false && strpos($url, '#') === false) {
                    // 外部链接，修改为 go.php 跳转
                    return '<a ' . $matches[1] . 'href="' . $siteUrl .  'go?url=' . $url. '"' . $matches[3] . '>';
                } else {
                    // 内部链接，保持不变
                    return '<a ' . $matches[1] . 'href="' . $url . '"' . $matches[3] . '>';
                }
            },
            $content
        );
}
*/
/**
 * 获取头像
 * @param $mail 邮箱
 * @package $uid 是否为注册用户
 */
function getAvatarByMail($mail, $uid)
{
    $enabletx = getOptions()->enabletx;
    if ($enabletx == 1) {
    if (empty($uid)) {
        $tx = 'guest';
    } else {
        $tx = 'member';
    }
    $cdnAddress = getOptions()->cdnAddress;
    $themeUrl = getoptions()->themeUrl;
    if (!empty($cdnAddress)) {
        $authorAvatar = $cdnAddress . 'images/' . $tx . '.svg';
    } else {
        $authorAvatar = $themeUrl . '/images/' . $tx . '.svg';
    }
      return $authorAvatar;
    }
  $gravatarsUrl = getOptions()->avatarlink;
  if (empty($gravatarsUrl)) {
      $gravatarsUrl = __TYPECHO_GRAVATAR_PREFIX__;
  }
  $mailLower = strtolower($mail);
  $md5MailLower = md5($mailLower);
    return $gravatarsUrl . $md5MailLower . '?d=mm';
}

/*
* 评论回复时 @ 评论人
*/
function get_comment_at($coid)
{
    $db   = Typecho_Db::get();
    $prow = $db->fetchRow($db->select('parent,status')->from('table.comments')
        ->where('coid = ?', $coid));
    $mail = "";
    $parent = @$prow['parent'];
    if ($parent != "0") {
        $arow = $db->fetchRow($db->select('author,status,mail')->from('table.comments')
            ->where('coid = ?', $parent));
        @$author = @$arow['author'];
        $mail = @$arow['mail'];
        if(@$author && $arow['status'] == 'approved'){
            if (@$prow['status'] == "waiting"){
                echo '<p>（审核中）</p>';
            }
            echo '<p><a href="#comment-' . $parent . '">@<strong>' . $author . '</strong></a></p>';
        }else{
            if (@$prow['status'] == 'waiting'){
                echo '<p>（审核中）</p>';
            }else{
                echo '';
            }
        }

    } else {
        if (@$prow['status'] == 'waiting'){
            echo '<p>（审核中）</p>';
        }else{
            echo '';
        }
    }
}

/**
 * 获取版权日期
 */
function getCopyrightDate(): string
{
  $text = '';
  if (!empty(getOptions()->startDate)) {
    $startDate = date_create(getOptions()->startDate);
    $text .= date_format($startDate, 'Y');
    $text .= '-';
  }
  $text .= date('Y', time());
  return $text;
}

/**
 * 获取文章归档
 * @param $widget
 * @return array
 */
function getArchives($widget)
{
  $db = Typecho_Db::get();
  $rows = $db->fetchAll(
    $db
      ->select()
      ->from("table.contents")
      ->order("table.contents.created", Typecho_Db::SORT_DESC)
      ->where("table.contents.type = ?", "post")
      ->where("table.contents.status = ?", "publish")
  );

  $stat = [];
  foreach ($rows as $row) {
    $row = $widget->filter($row);
    $arr = [
      "cid" => $row["cid"],
      "title" => $row["title"],
      "permalink" => $row["permalink"],
    ];
    $stat[date("Y", $row["created"])][$row["created"]] = $arr;
  }
  return $stat;
}
